<template>
  <PageModal
    :show="show"
    :title="$t('Dishwasher.customProgram.Title.Text')"
    :page-style="pageStyle"
    :footer-size="footerSize"
    :footer-style="footerStyle"
    @back="closeModal"
  >
    <view class="edit-favorite-program">
      <view v-if="!adjustParameterVisible" class="favorite-box">
        <view class="programs-box">
          <view class="title-box">
            <view class="title">{{ $t('Dishwasher.customProgram.SelectedProgram.Label.Text') }}</view>
            <view class="adjust" :class="{ disabled: saveDisabled }" @click="adjustParameter(true)">{{
              $t('Dishwasher.customProgram.AdjustParams.Label.Text')
            }}</view>
          </view>
          <!-- 程序列表 -->
          <ProgramList
            :programs="programs"
            :active-key="activeProgramKey"
            :active-tips="activeProgramRemaining"
            @select="onProgramSelect"
          />
        </view>
      </view>
    </view>

    <template #footer>
      <view class="btn-box">
        <TextButton
          class="text-button"
          size="large"
          :disabled="saveDisabled"
          :text="$t('Dishwasher.customProgram.Save.Button.Text')"
          @click="save"
        />
        <ActionButton
          v-if="isExistCustom"
          class="action-button"
          :disabled="activeProgramKey === ''"
          :text="$t('Dishwasher.customProgram.OnlyOneStart.Button.Text')"
          @click="onlyOneStart('Dishwasher.customProgram.OnlyOneStart.Button.Text')"
        />
      </view>
    </template>

    <!-- 调节参数 -->
    <AdjustParameterModal
      v-model:show="adjustParameterVisible"
      custom-footer
      :control="control"
      :no-prefix="!showFlexSprayPartition"
    >
      <template #prefix>
        <view v-if="control.store.flexSpraySupported">
          <ParameterCard>
            <view class="flex-spray">
              <view class="title">{{ control.store.flexSprayAdjustTitle }}</view>
              <view class="flex-spray-des">
                <text>{{ $t('Dishwasher.Flexspray.AdjustParams.Des.Before.Text') }}</text>
                <text class="flex-spray-highlight">{{ $t('Dishwasher.Flexspray.AdjustParams.Des.Middle.Text') }}</text>
                <text>{{ $t('Dishwasher.Flexspray.AdjustParams.Des.Last.Text') }}</text>
              </view>
              <view class="page-img-box">
                <PartitionView
                  type="adjust"
                  :haId="control.store._datasource.haId"
                  :programKey="control.store.currentProgramKey"
                  :programName="control.store.currentProgramName"
                  :flex-spray-list="flexSprayList || []"
                />
              </view>
            </view>
          </ParameterCard>
        </view>
      </template>
      <template #footer>
        <view class="btn-box">
          <TextButton
            class="text-button"
            size="large"
            :text="$t('Dishwasher.customProgram.AdjustParams.Save.Button.Text')"
            @click="save"
          />
          <ActionButton
            v-if="isExistCustom"
            class="action-button"
            :text="$t('Dishwasher.customProgram.AdjustParams.OnlyOneStart.Button.Text')"
            @click="onlyOneStart('Dishwasher.customProgram.AdjustParams.OnlyOneStart.Button.Text')"
          />
        </view>
      </template>
    </AdjustParameterModal>
  </PageModal>
</template>

<script setup lang="ts">
import ProgramList from '@/pages/appliance/components/programList.vue'
import AdjustParameterModal from '../../view/adjustParameterModal.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import ParameterCard from '../../components/parameterCard.vue'
import PartitionView from '../partitionView.vue'

import type { CSSProperties } from 'vue'
import { footerStyle, footerSize } from '@/layout/appliance/style'
import type { ApplianceProgram } from '@/types/appliance'
import { useI18n } from 'vue-i18n'
import { actionDebounce } from '@/utils/mpHelper'
import {
  BSH_COMMOM_PROGRAM_FAVORITE_001,
  BSH_COMMON_SETTING_FAVORITE_001_PROGRAM,
  DISHWASHER_SILTENT_ON_DEMAND,
  START_IN_RELATIVE,
} from '@/constants/Command'
import { setSetting, type ApplianceDetailOption } from '@/api/appliance'
import type { FavoriteOptType } from '../editFavoriteProgram/editFavoriteProgram.vue'
import { filterFavoritePrograms } from '@/controller/common/Program/FavoriteHelper'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import type { FlexSprayListType } from '../flexSpray/flexSpray.vue'
import type { DishwasherController } from '@/controller/Dishwasher/definition'
import TextButton from '@/common/textButton.vue'
import PageModal from '@/common/pageModal.vue'

const pageStyle: CSSProperties = {
  backgroundColor: '#ffffff',
}
const i18n = useI18n()

const props = defineProps<{
  show: boolean
  control: DishwasherController.Control
  flexSprayList?: FlexSprayListType[]
  showFlexSprayPartition?: boolean
}>()

const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
}>()

function closeModal() {
  adjustParameterVisible.value = false
  emit('update:show', false)
  emit('close')
}

const haId = computed(() => props.control.store._datasource.haId)
const programs = computed(() => filterFavoritePrograms(props.control.store.programs))
const activeProgramKey = computed(() => props.control.store.currentProgramKey)
const activeProgramName = computed(() => props.control.store.detail?.programName as string)
const activeProgramRemaining = computed(() => props.control.store.programRemainingText)
const currentOptions = computed(() => props.control.store.detail?.option || [])
const adjustParameterVisible = ref(false)
const isExistCustom = ref(false)

const saveDisabled = computed(() => {
  if (activeProgramKey.value === '' || /^BSH\.Common\.Program\.Favorite\.(\d+)$/.test(activeProgramKey.value)) {
    return true
  } else {
    return false
  }
})

watch(
  () => props.show,
  (show) => {
    if (show) {
      isExistCustom.value =
        props.control.store.allPrograms?.some((program) => program.key === BSH_COMMOM_PROGRAM_FAVORITE_001) || false
    }
  }
)

/**
 * slected program
 * @param program
 */
async function onProgramSelect(program: ApplianceProgram.Scope) {
  await props.control.store.setCurrentProgram(program)
}
/**
 * 显示调节参数
 */
function adjustParameter(value: boolean) {
  adjustParameterVisible.value = value
}
/**
 * 保存自定义程序
 */
const save = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    let submitParams: FavoriteOptType[] = [
      {
        key: activeProgramKey.value,
        name: activeProgramName.value,
        value: [],
      },
    ]
    let newOptions = clearOptions(currentOptions.value) || []

    // 处理精控强洗数据
    if (props.control.store.flexSpraySupported) {
      newOptions.forEach((option) => {
        props.flexSprayList?.forEach((item) => {
          if (option.key === item.key) {
            option.value = item.value
            option.displayvalue = item.displayvalue
          }
        })
      })
    }
    newOptions.forEach((item) => {
      submitParams[0].value.push({
        key: item.key as string,
        value: item.value as number,
        name: item.name as string,
      })
    })
    setTimeout(() => {
      closeModal()
    }, 300)
    let res: any = null
    try {
      res = await setSetting(haId.value, BSH_COMMON_SETTING_FAVORITE_001_PROGRAM, submitParams)
    } catch (error) {
      res = error
    } finally {
      // 埋点逻辑
      safeTrack(() => {
        type TackData = {
          program_name: string
          program_key: string
          [x: string]: unknown
        }
        let trackData: TackData = {
          program_name: '',
          program_key: '',
          successOrNot: res.code == 0,
          error_code: res.code,
          response_msg: res.msg,
        }
        trackData.program_name = submitParams[0].name
        trackData.program_key = submitParams[0].key
        trackData.favorite_value_obj = JSON.stringify({ ...submitParams[0].value })
        trackEvent('favorite_program', trackData, TrackType.ApplianceDetail, 'Appliance.CustomProgram.AddFavorite.Save')
      })
    }
    uni.showToast({
      title: i18n.t('APP.Common.SaveSucess.Text'),
      icon: 'success',
    })
  },
})
/**
 * 清除options中多余数据
 * @param list
 */
function clearOptions(list: ApplianceDetailOption[]) {
  try {
    return list.filter((item) => ![START_IN_RELATIVE, DISHWASHER_SILTENT_ON_DEMAND].includes(item.key))
  } catch (error) {}
}
/**
 * 仅本次启动
 */
const onlyOneStart = actionDebounce({
  call: async (buttonId?: string) => {
    const currentProgram = props.control.store.currentProgram as ApplianceProgram.Scope
    await props.control.store.startProgramNow(currentProgram, null, buttonId)
    closeModal()
  },
})
</script>

<style scoped lang="less">
.flex-spray {
  font-family: 'PingFang SC';
  font-style: normal;
  .title {
    font-weight: 500;
    font-size: 28rpx;
    line-height: 40rpx;
    color: var(--dark-color);
    padding: 0 24rpx;
  }
  .flex-spray-des {
    font-weight: 400;
    font-size: 24rpx;
    line-height: 34rpx;
    color: var(--dark-color);
    margin-top: 16rpx;
    margin-bottom: 8rpx;
    padding: 0 24rpx;
    .flex-spray-highlight {
      font-weight: 500;
      color: var(--primary-color);
    }
  }
  .page-img-box {
    width: 100%;
    height: 652rpx;
    padding: 24rpx 24rpx 0rpx;
    background-color: #f4f4f6;
    box-sizing: border-box;
    position: relative;
  }
}

.favorite-box {
  height: 100%;
  .disabled {
    opacity: 0.4;
    pointer-events: none;
  }
  .programs-box {
    height: 100%;
    box-sizing: border-box;
    overflow: scroll;
    padding-top: 48rpx;

    .title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 32rpx;
      .title {
        font-weight: 600;
        font-size: 48rpx;
        color: var(--dark-color);
      }
      .adjust {
        font-weight: 600;
        font-size: 28rpx;
        color: var(--primary-color);
      }
    }
  }
}
.btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 32rpx;
  line-height: 44rpx;
  .text-button {
    min-width: 240rpx;
    flex-grow: 1;
  }
  .action-button {
    flex-grow: 2;
  }
}
</style>
